package com.banyuan.servlet.types;

import com.alibaba.fastjson.JSON;
import com.banyuan.dao.TypesDao;
import com.banyuan.domain.ResData;
import com.banyuan.domain.Types;
import com.banyuan.utils.AuthorUtils;
import com.banyuan.utils.CommonUtils;
import com.banyuan.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/types/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String intro = req.getParameter("intro");

        //1。判断传进来的值
        if (CommonUtils.isEmpty(name) || CommonUtils.isEmpty(intro)) {
            ResData resData = new ResData(10001,"输入项为空",null);
            resp.getWriter().write(JSON.toJSONString(resData));
            return; //阻断下面代码的运行
        }


        // 2去数据库里查询name是否重复
        // 3.要是不重复的话，就添加到数据库
        ResultSet resultSet = null;
        try {
            resultSet = TypesDao.selectByName(name);
            resultSet.next();
            int countSum = resultSet.getInt("countSum");
            if (countSum > 0) {
                // 如果统计出来大于0 就是名字重复了
                ResData resData = new ResData(10002,"分类名称重复了，请换一个",null);
                resp.getWriter().write(JSON.toJSONString(resData));
                return; //阻断下面代码的运行
            } else {

                // 要通过session取出author的用户名 存储到types里
                Types types = new Types();
                String userName = AuthorUtils.getLoginUserName(req);
                types.setOperator(userName);
                types.setName(name);
                types.setIntro(intro);

                int insert = TypesDao.insert(types);
                if (insert > 0) {
                    ResData resData = new ResData(200,"添加成功",null);
                    resp.getWriter().write(JSON.toJSONString(resData));
                } else {
                    ResData resData = new ResData(10003,"添加失败，稍后再试",null);
                    resp.getWriter().write(JSON.toJSONString(resData));
                }


            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.closeBy(resultSet);
        }





    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
